<template>
  <div class="min-h-screen flex items-center justify-center p-8 ">
    <img src="../../public/images/login-bg.png" alt="background" class="w-screen m-0 z-0 fixed" />
    <div class="relative max-w-md bg-cover bg-center bg-white shadow-2xl rounded-2xl bg-no-repeat h-full p-4 md:p-12">
      <div class="text-blue-400 text-center">
        <img src="../../public/images/login-title.png" alt="background" class="mb-4" />
        <h2 class="text-2xl font-bold mb-4">About Our Skin Disease Recognition Project</h2>
        <p class="text-lg">
          Lorem ipsum dolor sit amet, consectetur adipiscing elit. Our project aims to provide a robust and accurate skin disease recognition system using advanced machine learning techniques.
        </p>
        <!-- 你可以在这里添加更多的信息或按钮 -->
      </div>
    </div>
    <div class="max-w-md w-full bg-white shadow-2xl rounded-2xl overflow-hidden md:w-3/4 lg:w-1/2 z-50">
      <div class="px-8 py-10">
        <h2 v-if="!showRegisterForm" class="text-2xl font-bold text-blue-400 mb-6">Sign In</h2>
        <h2 v-if="showRegisterForm" class="text-2xl font-bold text-blue-400 mb-6">Sign Up</h2>
        <form @submit.prevent="handleLogin">
          <div v-if="!showRegisterForm" class="mb-6 relative">
            <label for="email" class="block text-sm font-medium text-gray-700 mb-1">
              Email
            </label>
            <input
                type="email"
                id="email"
                class="block w-full px-4 py-2 mt-1 text-sm text-gray-700 bg-gray-50 border border-gray-300 rounded-lg focus:outline-none focus:ring-blue-400 focus:border-blue-400"
                placeholder="Your email"
                v-model="email"
                required
            />
          </div>
          <div v-if="!showRegisterForm" class="mb-6 relative">
            <label for="password" class="block text-sm font-medium text-gray-700 mb-1">
              Password
            </label>
            <input
                type="password"
                id="password"
                class="block w-full px-4 py-2 mt-1 text-sm text-gray-700 bg-gray-50 border border-gray-300 rounded-lg focus:outline-none focus:ring-blue-400 focus:border-blue-400"
                placeholder="Your password"
                v-model="password"
                required
            />
            <span class="absolute right-3 top-3/4 mb-2 transform -translate-y-1/2 cursor-pointer" @click="togglePasswordVisibility('password')"> <!-- 添加眼睛图标及点击事件 -->
                    <i v-if="!passwordVisible.password" class="far fa-eye-slash text-gray-400"></i> <!-- 使用Font Awesome图标库，未显示时是闭眼图标 -->
                    <i v-if="passwordVisible.password" class="far fa-eye text-gray-400"></i> <!-- 使用Font Awesome图标库，显示时是睁眼图标 -->
                </span>
          </div>
          <div v-if="!showRegisterForm" class="mb-6">
            <button
                type="submit"
                class="block w-full text-center text-white bg-blue-400 border border-transparent rounded-lg py-3 px-4 hover:bg-blue-500 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-400"
            >
              Sign In
            </button>
          </div>
          <div v-if="!showRegisterForm" class="flex justify-center items-center mt-4">
            <div class="text-sm text-gray-500 mr-2">
              <a href="#" @click.prevent="gotoHome" class="hover:text-blue-500 hover:underline">游客浏览</a>
              <a href="#" @click.prevent="toggleRegisterForm" class="hover:text-blue-500 hover:underline">Don't have an account? Sign Up</a>
            </div>
          </div>
          <div v-if="showRegisterForm" class="mb-6 relative">
            <label for="newEmail" class="block text-sm font-medium text-gray-700 mb-1">
              New Email
            </label>
            <input
                type="email"
                id="newEmail"
                class="block w-full px-4 py-2 mt-1 text-sm text-gray-700 bg-gray-50 border border-gray-300 rounded-lg focus:outline-none focus:ring-blue-400 focus:border-blue-400"
                placeholder="Your new email"
                v-model="newEmail"
                required
            />
          </div>
          <div v-if="showRegisterForm" class="mb-6 relative">
            <label for="newPassword" class="block text-sm font-medium text-gray-700 mb-1">
              New Password
            </label>
            <input
                type="password"
                id="newPassword"
                class="block w-full px-4 py-2 mt-1 text-sm text-gray-700 bg-gray-50 border border-gray-300 rounded-lg focus:outline-none focus:ring-blue-400 focus:border-blue-400"
                placeholder="Your new password"
                v-model="newPassword"
                required
            />
            <span class="absolute right-3 top-3/4 transform -translate-y-1/2 cursor-pointer" @click="togglePasswordVisibility('newPassword')"> <!-- 添加眼睛图标及点击事件 -->
                    <i v-if="!passwordVisible.newPassword" class="far fa-eye-slash text-gray-400"></i> <!-- 使用Font Awesome图标库，未显示时是闭眼图标 -->
                    <i v-if="passwordVisible.newPassword" class="far fa-eye text-gray-400"></i> <!-- 使用Font Awesome图标库，显示时是睁眼图标 -->
                </span>
          </div>
          <div v-if="showRegisterForm" class="mb-6 relative">
            <label for="repeatPassword" class="block text-sm font-medium text-gray-700 mb-1">
              Repeat Password
            </label>
            <input
              type="password"
              id="repeatPassword"
              class="block w-full px-4 py-2 mt-1 text-sm text-gray-700 bg-gray-50 border border-gray-300 rounded-lg focus:outline-none focus:ring-blue-400 focus:border-blue-400"
              placeholder="Please repeat your password"
              v-model="repeatPassword"
              required
            />
            <span class="absolute right-3 top-3/4 transform -translate-y-1/2 cursor-pointer" @click="togglePasswordVisibility('repeatPassword')"> <!-- 添加眼睛图标及点击事件 -->
                    <i v-if="!passwordVisible.repeatPassword" class="far fa-eye-slash text-gray-400"></i> <!-- 使用Font Awesome图标库，未显示时是闭眼图标 -->
                    <i v-if="passwordVisible.repeatPassword" class="far fa-eye text-gray-400"></i> <!-- 使用Font Awesome图标库，显示时是睁眼图标 -->
                </span>
          </div>
          <div v-if="showRegisterForm" class="mb-6">
            <button
                type="button"
                class="block w-full text-center text-white bg-blue-400 border border-transparent rounded-lg py-3 px-4 hover:bg-blue-500 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-400"
                @click="handleRegister"
            >
              Register
            </button>
          </div>
          <div v-if="showRegisterForm" class="flex justify-center items-center mt-4">
            <div class="text-sm text-gray-500 mr-2">
              <a href="#" @click.prevent="toggleRegisterForm" class="hover:text-blue-500 hover:underline">Already have an account? Sign In</a>
            </div>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>
<script setup lang="ts">
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import axiosInstance from '../axios.js';
import { far } from '@fortawesome/free-regular-svg-icons';

// 控制注册表单显示隐藏的响应式变量，初始为 false，表示隐藏
const showRegisterForm = ref(false);
const newEmail = ref<string>('');
const newPassword = ref<string>('');
const repeatPassword = ref<string>('');

const handleRegister = async () => {
  // 先验证是否输入了邮箱、密码以及两次输入的密码是否一致
  if (!newEmail.value) {
    alert('请输入邮箱');
    return;
  }
  if (!newPassword.value) {
    alert('请输入密码');
    return;
  }
  if (!repeatPassword.value) {
    alert('请再次输入密码');
    return;
  }
  if (newPassword.value!== repeatPassword.value) {
    alert('两次输入的密码不一致，请重新输入');
    return;
  }
  try {
    const response = await axiosInstance.post('/users/register', { email: newEmail.value, password: newPassword.value});
    if (response.data.success) {
      // 注册成功后，将新注册的邮箱保存到localStorage
      localStorage.setItem('userEmail', newEmail.value);
      alert(response.data.message);
    } else {
      alert(response.data.message);
    }
  } catch (error) {
    console.error('Error during registration:', error);
    alert('An error occurred during registration. Please try again later.');
  }
};

const email = ref<string>('');
const password = ref<string>('');
const router = useRouter();

const gotoHome = () => {
  router.push('/Home');
};
const handleLogin = async () => {
  try {
    const fullUrl = axiosInstance.defaults.baseURL + '/users/login';
    console.log('即将发送的登录请求完整 URL:', fullUrl);
    const response = await axiosInstance.post('/users/login', {
      email: email.value,
      password: password.value,
    });
    if (response.data.success) {
      // 登录成功后，将邮箱保存到localStorage
      localStorage.setItem('userEmail', email.value);
      await router.push('/Home');
    } else {
      alert(response.data.message || 'Invalid email or password');
    }
  } catch (error) {
    if (error.response) {
      // 服务器响应了一个状态码，可以根据状态码显示不同的错误消息
      console.error('Server error:', error.response.status, error.response.data);
      alert(`Server error: ${error.response.status}. Please try again later.`);
    } else if (error.request) {
      // 请求已经发出，但没有收到响应
      console.error('No response received:', error.request);
      alert('No response received from the server. Please check your network connection.');
    } else {
      // 其他错误，如设置请求时发生的错误
      console.error('Error setting up request:', error.message);
      alert('An error occurred during login. Please try again later.');
    }
  }
};
const passwordVisible = ref({
  password: false,
  newPassword: false,
  repeatPassword: false
});

const togglePasswordVisibility = (passwordField: string) => {
  passwordVisible.value[passwordField] =!passwordVisible.value[passwordField];
  const inputElement = document.getElementById(passwordField) as HTMLInputElement;
  if (passwordVisible.value[passwordField]) {
    inputElement.type = 'text';
  } else {
    inputElement.type = 'password';
  }
};
// 用于切换显示注册表单的方法
const toggleRegisterForm = () => {
  showRegisterForm.value =!showRegisterForm.value;
};
// 注册Font Awesome图标库使用
const icons = { far };
</script>
<style scoped>
@import url('https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css'); /* 引入Font Awesome图标库样式，可根据实际情况调整引入方式 */
</style>